package com.ldx.java_chatroom.controller;

import com.ldx.java_chatroom.service.UserService;
import com.ldx.java_chatroom.model.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {
    @Resource
    UserService userService;
    @RequestMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest rep){
        User user = userService.login(username);
        if(user==null||!password.equals(user.getPassword())){
            System.out.println("登录失败，用户名或密码错误"+user);
            return new User();
        }
        //如果都匹配，创建会话
        HttpSession session = rep.getSession(true);
        session.setAttribute("User",user);
        user.setPassword("");
        return user;
    }
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        User user = null;
        try {
            user = new User();
            user.setPassword(password);
            user.setUsername(username);
            int ret = userService.insert(user);
            System.out.println("注册"+user);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            //如果名字重复，insert方法抛出上述异常，注册失败
            user = new User();
            System.out.println("注册失败! username="+username);
        }

        return user;
    }
    @GetMapping("/userInfo")
    @ResponseBody
    public User getUserInfo( HttpServletRequest rep){
        HttpSession session = rep.getSession(false);
        if(session == null){
            return new User();
        }
        User user = (User) session.getAttribute("User");
        if(user == null){
            return new User();
        }
        return user;
    }

}
